package com.bootdo.clouddo.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.clouddo.utils.R;
import com.bootdo.clouddo.utils.StringUtils;
import com.bootdo.clouddo.utils.book.HttpUtils;
import com.google.common.base.Charsets;
import org.apache.commons.lang3.CharSet;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/cll")
public class CllApiController {

    @GetMapping("/api")
    public String getVideos(String url, HttpServletRequest request) {
        try {
            if(StringUtils.isEmpty(url)) {
                return "url_empty";
            }
            Map<String, String> params = new HashMap<>();
            Enumeration<String> parameterNames = request.getParameterNames();
            while (parameterNames.hasMoreElements()){
                String key = parameterNames.nextElement();
                params.put(key, request.getParameter(key));
            }
            params.remove("url");
            String resultVo = sendGetRequest(url, params, request.getHeader("content-type"));
            if(resultVo != null) {
                return resultVo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String sendGetRequest(String url, Map<String, String> params, String contentType) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        Map<String, String> h = new HashMap<>();
        h.put("Referer", "https://servicewechat.com/wx71d589ea01ce3321/401/page-frame.html");
        return HttpUtils.doGet(url, h, params, Charsets.UTF_8.name()).getBody();
    }
}
